var express = require('express');
const FileSync = require('lowdb/adapters/FileSync')
const {formidable}=require('formidable')
const low = require('lowdb')
const shortid = require('shortid')
var router = express.Router();
//修改默认路径
const adapter = new FileSync(__dirname+'/../data/db.json')
const db = low(adapter)

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
//新增事件
router.post('/account', function(req, res, next) {
  // console.log(req,'>>>req.body');
  db.get('account').unshift({id: shortid.generate(),...req.body}).write()
  res.render('tips',{msg:"新增成功啦",url:'/account/edit'})
});

//编辑页面展示
router.get('/account/edit', function(req, res, next) {
  res.render('edit',{info:db.get('account').value()});
});


//通过id删除
router.get('/account/:id', function(req, res, next) {
  let id=req.params.id
  db.get('account').remove({id}).write()
  res.send('删除成功')
});

//文件处理
router.post('/fileup', function(req, res, next) {
  const form = formidable({
    uploadDir:__dirname+'../../public/images',
    keepExtensions
  });

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    //fidlds基础类型数据 files存储流文件
    const imgUrl='/images/'+files.userpic[0].newFilename
    // res.json({ fields, files });
    res.send(imgUrl)
  });
});

module.exports = router;
